using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace M13.Game.World
{
    public class ChunkObject
    {
        private static Queue<GameObject> _chunkObjPool = new Queue<GameObject>();
        public static GameObject ChunkInstantiate(Vector2Int chunkLocalCoord, ChunkMesh chunkMesh, Transform worldTransform)
        {
            if (_chunkObjPool.Count > 0)
            {
                GameObject chunkObj = _chunkObjPool.Dequeue();
                chunkObj.SetActive(true);
                chunkObj.name = $"Chunk{chunkLocalCoord}";
                chunkObj.tag = "Chunk";
                chunkObj.transform.SetParent(worldTransform);
                chunkObj.transform.position = new Vector3(chunkLocalCoord.x * 16, 0, chunkLocalCoord.y * 16);
                chunkObj.GetComponent<MeshFilter>().mesh = chunkMesh.Mesh;
                chunkObj.GetComponent<MeshRenderer>().materials = ResourceKey.TurfMaterials.Materials;
                return chunkObj;
            }
            else
            {
                GameObject chunkObj = new GameObject($"Chunk{chunkLocalCoord}");
                chunkObj.transform.SetParent(worldTransform);
                chunkObj.tag = "Chunk";
                chunkObj.transform.position = new Vector3(chunkLocalCoord.x * 16, 0, chunkLocalCoord.y * 16);
                chunkObj.AddComponent<MeshFilter>().mesh = chunkMesh.Mesh;
                chunkObj.AddComponent<MeshRenderer>().materials = ResourceKey.TurfMaterials.Materials;
                chunkObj.AddComponent<MeshCollider>();
                return chunkObj;
            }
        }

        public static void ChunkObjectRecycle(GameObject chunkObj)
        {
            chunkObj.SetActive(false);
            _chunkObjPool.Enqueue(chunkObj);
        }

        public static int GetChunkObjectCount()
        {
            return _chunkObjPool.Count;
        }
    }
}